from keystoneauth1 import session
from keystoneauth1.identity import v3
from gnocchiclient.v1 import client
import numpy

password = v3.PasswordMethod(username='admin',
                                password='bjtungirc',
                                user_domain_name='Default')
auth = v3.Auth(auth_url='http://controller:5000/v3',
                auth_methods=[password],
                project_id='54f3f02468f74f16aa96c3194d6474b4')
sess = session.Session(auth=auth)

gnocchi = client.Client(sess)

def get_instance_cpu_util(id):
    """获取虚拟机的cpu利用率

    根据虚拟机id获取虚拟机的cpu利用率

    参数：
        id: 虚拟机id

    返回值：
        cpu利用率
    """
    last_three = gnocchi.metric.get_measures('cpu_util', resource_id=id)[-2:]
    if last_three:
        cpu_util = [x[-1] for x in last_three]
        return numpy.mean(cpu_util)
    else:
        return 0

def get_instance_vcpus(id):
    """获取虚拟机cpu的正在运行的核数。

    根据虚拟机id获取虚拟机cpu正在运行的核数。

    参数：
        id: 虚拟机id

    返回值：
        cpu正在运行的核数
    """
    return int(gnocchi.metric.get_measures('vcpus', resource_id=id)[-1][-1])
